package com.example.storage;

import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class Shared_preferencesActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_shared_preferences);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
         EditText username = (EditText)  findViewById(R.id.Shared_preferences_username);
         EditText userpassword = (EditText)  findViewById(R.id.Shared_preferences_userpassword);
         ((Button) findViewById(R.id.Shared_preferences_submit)).setOnClickListener(v -> {
             String username_text = username.getText().toString();
             String userpassword_text = userpassword.getText().toString();
             if (username_text.isEmpty() || userpassword_text.isEmpty()) {
                 Toast.makeText(this, "请输入用户名或密码", Toast.LENGTH_SHORT).show();
                 return;
             }

            getSharedPreferences("", MODE_PRIVATE).edit()
                    .putString("username", username_text)
                    .putString("userpassword", userpassword_text)
                    .commit();
             Toast.makeText(this, "username:" + username_text + "userpassword:" + userpassword_text, Toast.LENGTH_SHORT).show();
         });
         ((Button) findViewById(R.id.Shared_preferences_File)).setOnClickListener(v -> {
            // 读取
             String username_text = getSharedPreferences("", MODE_PRIVATE).getString("username", "");
             String userpassword_text = getSharedPreferences("", MODE_PRIVATE).getString("userpassword", "");
             if (username_text.isEmpty() || userpassword_text.isEmpty()) {
                 Toast.makeText(this, "读取错误", Toast.LENGTH_SHORT).show();
                 return;
             }else{
                 username.setText(username_text);
                 userpassword.setText(userpassword_text);
             }
         });
    }
}